<template>
  <div class="farm-detail-container">
    <div class="header">
      <el-button @click="handleBack">返回</el-button>
      <p>新增农场</p>
    </div>
    <el-card shadow="always" style="width: 100%">
      <template #header>
        <div style="font-size: 16px; font-weight: 600">农场信息</div>
      </template>
      <div class="farm-part">
        <!-- 农场信息部分 -->
        <div class="farm-form">
          <el-form
            :model="farmForm"
            label-width="120px"
            :label-position="'top'"
          >
            <div class="farm-form-top">
              <el-form-item label="农场名称">
                <el-input v-model="farmForm.name" />
              </el-form-item>
              <el-form-item label="所在地区">
                <el-select v-model="farmForm.region" placeholder="请选择">
                  <el-option label="杭州滨江区" value="杭州滨江区" />
                </el-select>
              </el-form-item>
              <el-form-item label="农场面积(亩)">
                <el-input v-model="farmForm.area" />
              </el-form-item>
              <el-form-item label="状态">
                <el-radio-group v-model="farmForm.status">
                  <el-radio value="1" size="large">在业</el-radio>
                  <el-radio value="2" size="large">停业</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="农场位置">
                <!-- 地图部分 -->
                <div class="map-container">
                  <div style="display: flex">
                    <div style="width: 200px; margin-right: 20px">
                      <el-form-item label="中心点经度">
                        <el-input
                          type="number"
                          v-model="formFarmInfo.lnglatLng"
                          step="0.000001"
                          placeholder="点击地图或搜索设置"
                        />
                      </el-form-item>
                      <el-form-item label="中心点纬度">
                        <el-input
                          type="number"
                          v-model="formFarmInfo.lnglatLat"
                          step="0.000001"
                          placeholder="点击地图或搜索设置"
                        />
                      </el-form-item>
                      <el-form-item label="半径">
                        <el-input
                          type="number"
                          v-model="formFarmInfo.radius"
                          placeholder="点击地图或搜索设置"
                        />
                      </el-form-item>
                      <el-form-item>
                        <el-button
                          type="primary"
                          style="width: 100%; margin-bottom: 20px"
                          @click="clickDrawCircle"
                          >绘制圆形区域</el-button
                        >
                        <div style="width: 100%">
                          <el-button
                            plain
                            style="width: 100%"
                            @click="clickResetMap"
                            >重置地图</el-button
                          >
                        </div>
                      </el-form-item>
                    </div>
                    <div style="flex: 1">
                      <MapContainer
                        ref="mapContainerRef"
                        :lnglatLng="formFarmInfo.lnglatLng"
                        :lnglatLat="formFarmInfo.lnglatLat"
                        :radius="formFarmInfo.radius"
                        @coordinate-change="handleCoordinateChange"
                      />
                    </div>
                  </div>
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
    </el-card>
    <el-card style="width: 100%">
      <template #header>
        <div style="font-size: 16px; font-weight: 600">区域信息</div>
      </template>
      <EditTable
        v-model="areaList"
        :columns="areaCols"
        :emptyRowFactory="() => ({ name: '', crop: '', area: 0 })"
        :addTitle="'区域'"
        @update:modelValue="(val) => (areaList = val)"
        @row-delete="onRowDelete"
      />
    </el-card>

    <el-card style="width: 100%">
      <template #header>
        <div style="font-size: 16px; font-weight: 600">灌溉程序信息</div>
      </template>
      <EditTable
        v-model="programList"
        :columns="programCols"
        :switch-enabled="true"
        :addTitle="'程序'"
        @update:modelValue="(val) => (programList = val)"
        :emptyRowFactory="
          () => ({ name: '', code: '', region: [], enable: true })
        "
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import router from "@/router";
import EditTable, { type EditColumn } from "@/components/EditTable.vue";
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import MapContainer from "./components/MapContainer.vue";

// 表单数据
const formFarmInfo = reactive({
  farmName: "", // 农场名称
  lnglatLng: "", // 经度
  lnglatLat: "", // 纬度
  radius: "500", // 半径
});

// 获取MapContainer组件的引用
const mapContainerRef = ref<InstanceType<typeof MapContainer> | null>(null);

/**
 * 绘制圆形区域
 */
function clickDrawCircle() {
  // 验证表单数据
  if (
    !formFarmInfo.lnglatLng ||
    !formFarmInfo.lnglatLat ||
    !formFarmInfo.radius
  ) {
    ElMessage.error("请先设置有效的坐标和半径值！");
    return;
  }

  const lng = parseFloat(formFarmInfo.lnglatLng);
  const lat = parseFloat(formFarmInfo.lnglatLat);
  const radius = parseFloat(formFarmInfo.radius.toString());

  // 验证数值有效性
  if (isNaN(lng) || isNaN(lat) || isNaN(radius)) {
    ElMessage.error("请输入有效的数值！");
    return;
  }

  if (radius <= 0) {
    ElMessage.error("半径必须大于0！");
    return;
  }

  // 调用MapContainer组件的drawCircle法绘制圆形
  if (
    mapContainerRef.value &&
    typeof mapContainerRef.value.drawCircle === "function"
  ) {
    mapContainerRef.value.drawCircle(lng, lat, radius);
  } else {
    ElMessage.error("地图组件尚未完全加载，请稍后再试！");
  }
}

/**
 * 处理地图点击事件，更新经纬度
 */
function handleCoordinateChange(lng: string, lat: string) {
  formFarmInfo.lnglatLng = lng;
  formFarmInfo.lnglatLat = lat;
}

/**
 * 重置地图
 */
function clickResetMap() {
  // 清空表单数据
  formFarmInfo.lnglatLng = "";
  formFarmInfo.lnglatLat = "";
  formFarmInfo.radius = "500";

  // 提示用户
  ElMessage.success("地图已重置！");

  // 如果需要，可以在这里添加更多的重置逻辑
  // 例如，如果MapContainer组件提供了重置方法，可以调用它
  if (
    mapContainerRef.value &&
    typeof mapContainerRef.value.resetMap === "function"
  ) {
    mapContainerRef.value.resetMap();
  }
}

// 返回按钮处理
const handleBack = () => {
  router.push("/farmManagement/index");
};

// 定义农场信息的类型
interface Farm {
  name: string;
  region: string[];
  lng: string;
  lat: string;
  area: string;
  status: string;
}

// 定义区域信息的类型
interface Area {
  name: string;
  crop: string;
  area: number | string;
}

// 定义灌溉程序信息的类型
interface Program {
  name: string;
  code: string;
  region: string[];
  enable: boolean;
}

// 1. 农场信息
const farmForm = reactive<Farm>({
  name: "安吉农场",
  region: ["浙江", "安吉"],
  lng: "108.30",
  lat: "22.87",
  area: "108.30",
  status: "1",
});

// 2. 区域信息
const areaList = ref<Area[]>([
  { name: "45号棚", crop: "蓝莓", area: 20 },
  { name: "46号棚", crop: "草莓", area: 30 },
  { name: "其他", crop: "草莓", area: 50 },
]);

const areaCols: EditColumn<Area>[] = [
  { prop: "name", label: "区域名称" },
  { prop: "crop", label: "种植作物" },
  {
    prop: "area",
    label: "面积",
    type: "number",
    min: 0,
    precision: 2,
  },
];

// 3. 灌溉程序信息
const programList = ref<Program[]>([
  { name: "程序1", code: "a", region: ["46号棚"], enable: true },
  { name: "程序2", code: "b", region: ["45号棚"], enable: false },
]);

const programCols: EditColumn<Program>[] = [
  { prop: "name", label: "区域名称" },
  { prop: "code", label: "种植作物" },
  {
    prop: "region",
    label: "关联区域",
    type: "select",
    multiple: true,
    options: [
      { label: "45号棚", value: "45号棚" },
      { label: "46号棚", value: "46号棚" },
      { label: "48号棚", value: "48号棚" },
      { label: "49号棚", value: "49号棚" },
      { label: "50号棚", value: "50号棚" },
      { label: "51号棚", value: "51号棚" },
      { label: "52号棚", value: "52号棚" },
    ],
  },
  { prop: "enable", label: "状态", type: "switch" },
];

// 事件处理
const onRowDelete = (rowData: Area[]) => {
  if (rowData.length) {
    const data = rowData[0];
    let newList: Program[] = [];
    programList.value.forEach((item) => {
      const obj: Program = item;
      if (item.region.includes(data.name)) {
        obj.region = item.region.filter((val) => val !== data.name);
        newList.push(obj);
      } else {
        newList.push(obj);
      }
    });
    programList.value = newList;
  }
};
</script>

<style lang="scss" scoped>
.farm-detail-container {
  padding: 20px;
  .el-card {
    margin-bottom: 20px;
  }
  .el-card__header {
    border-bottom: none;
  }
  overflow: auto;

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  .farm-part {
    width: 100%;
    display: flex;
    .farm-form {
      width: 100%;
      .farm-form-top {
        display: flex;
        .el-form-item {
          width: 24%;
          margin-right: 20px;
        }
      }
    }
    .map-container {
      flex: 1;
      .el-form-item {
        margin-bottom: 20px;
      }
    }
  }
  #map-mapContainer {
    width: 100%;
    height: 400px; /* 可根据需求调整 */
  }
  .el-divider {
    margin: 36px 0 16px;
  }
}
</style>
